import React from 'react';
import cn from 'classnames';
import { Card } from 'antd';
import styles from './index.less';

const images = ['jpg', 'jpeg', 'png'];
const FilePreview = ({ title = '制度文件', url, height = 600, ...rest }) => {
    // 根据文件名返回格式，比如a.pdf 返回pdf
    const getFileType = file => {
        if (file) {
            const realName = decodeURIComponent(file);
            const start = realName.lastIndexOf('.');
            return realName.substring(start + 1, realName.length).toLowerCase();
        }
        return '';
    };
    const renderIframe = () => {
        if (url) {
            const docUrl = encodeURIComponent(url);
            const type = getFileType(docUrl);
            if (images.includes(type)) {
                return (
                    <div className={styles.textWrap} style={{ height }}>
                        <div className={styles.maskTop}>微微科技内部文件，仅供查看</div>
                        <div className={styles.maskBottom} />
                        <div
                            style={{
                                width: '100%',
                                height: '100%',
                                overflow: 'auto',
                                padding: '88px 0 15px'
                            }}
                        >
                            <img
                                src={url}
                                alt="法律条款"
                                style={{ display: 'block', width: '80%', maxWidth: 1000, margin: '0 auto' }}
                            />
                        </div>
                    </div>
                );
            }
            const finalUrl = `https://view.officeapps.live.com/op/view.aspx?src=${docUrl}`;
            return (
                <div className={cn(styles.textWrap, styles[getFileType(url)])} style={{ height }}>
                    <div className={styles.maskTop}>
                        <i className={styles.logo} />
                        微微科技内部文件，仅供查看
                    </div>
                    <div className={styles.maskBottom} />
                    <div style={{ width: '100%', overflow: 'auto' }}>
                        <iframe
                            title={title}
                            style={{
                                width: '100%',
                                minWidth: '800px',
                                height,
                                border: 0
                            }}
                            src={finalUrl}
                        ></iframe>
                    </div>
                </div>
            );
        }
        return '';
    };

    return (
        <Card bordered={false} {...rest}>
            {renderIframe()}
        </Card>
    );
};

export default FilePreview;
